<template>
  <view class="history-container">
    <!-- 顶部导航栏 -->
    <view class="nav-bar">
      <view class="nav-title">历史对话</view>
      <view class="nav-actions">
        <view class="back-btn" @tap="goBack">
          <image src="/static/fanhui.png" class="back-icon"></image>
          <text>返回</text>
        </view>
      </view>
    </view>

    <!-- 历史对话列表 -->
    <scroll-view class="history-list" scroll-y="true">
      <view v-if="loading" class="loading-container">
        <text class="loading-text">加载中...</text>
      </view>
      
      <view v-else-if="subjects.length === 0" class="empty-container">
        <text class="empty-text">暂无历史对话</text>
      </view>
      
      <view v-else>
        <view 
          v-for="subject in subjects" 
          :key="subject.subject_id" 
          class="history-item"
          @tap="viewChatHistory(subject)"
        >
          <view class="subject-info">
            <text class="subject-name">{{ subject.subject_name || '未命名对话' }}</text>
            <text class="subject-time">{{ formatTime(subject.created_at) }}</text>
          </view>
          <view class="action-buttons">
            <view class="continue-btn" @tap.stop="continueChat(subject)">
              继续对话
            </view>
            <view class="delete-btn" @tap.stop="confirmDelete(subject)">
              删除
            </view>
          </view>
        </view>
      </view>
    </scroll-view>

    <!-- 聊天历史详情弹窗 -->
    <view v-if="showChatDetail" class="chat-detail-modal">
      <view class="modal-content">
        <view class="modal-header">
          <text class="modal-title">{{ currentSubject?.subject_name || '对话详情' }}</text>
          <view class="close-btn" @tap="closeChatDetail">×</view>
        </view>
        
        <scroll-view class="chat-content" scroll-y="true">
          <view v-if="chatHistoryLoading" class="loading-container">
            <text class="loading-text">加载对话内容...</text>
          </view>
          
          <view v-else-if="chatHistory.length === 0" class="empty-container">
            <text class="empty-text">暂无对话内容</text>
          </view>
          
          <view v-else>
            <view 
              v-for="chat in chatHistory" 
              :key="chat.chat_id" 
              class="chat-message"
              :class="{ 'user-message': chat.question, 'ai-message': chat.answer }"
            >
              <view v-if="chat.question" class="message-content user-content">
                <text class="user-id">用户ID: {{ user_id }}</text>
                <text class="message-text">{{ chat.question }}</text>
              </view>
              <view v-if="chat.answer" class="message-content ai-content">
                <text class="user-id">用户ID: 000</text>
                <text class="message-text">{{ chat.answer }}</text>
              </view>
              <text class="message-time">{{ formatTime(chat.created_at) }}</text>
            </view>
            
            <!-- 继续对话按钮 -->
            <view class="continue-chat-btn-container">
              <button class="continue-chat-btn" @tap="continueChat">继续对话</button>
            </view>
          </view>
        </scroll-view>
      </view>
    </view>

    <!-- 删除确认对话框 -->
    <view class="delete-confirm-modal" v-if="showDeleteConfirm">
      <view class="modal-content">
        <view class="modal-header">
          <text class="modal-title">确认删除</text>
        </view>
        <view class="modal-body">
          <text class="confirm-text">确定要删除这个历史对话吗？删除后将无法恢复。</text>
        </view>
        <view class="modal-footer">
          <view class="cancel-btn" @tap="cancelDelete">取消</view>
          <view class="confirm-delete-btn" @tap="performDelete">确认删除</view>
        </view>
      </view>
    </view>
  </view>
</template>

<script>
import { getSubjects, getChatHistory, deleteSubject } from '@/api/api.js';

export default {
  data() {
    return {
      user_id: 0,
      subjects: [],
      loading: false,
      showChatDetail: false,
      currentSubject: null,
      chatHistory: [],
      chatHistoryLoading: false,
      showDeleteConfirm: false,
      deleteSubject: null
    }
  },
  
  onLoad() {
    this.initUserInfo()
    this.loadSubjects()
  },
  
  methods: {
    initUserInfo() {
      try {
        const currentUser = uni.getStorageSync('currentUser')
        if (currentUser) {
          this.user_id = currentUser.user_id || currentUser.id || 0
          console.log('获取到用户ID:', this.user_id)
        } else {
          console.warn('未找到用户信息，请先登录')
          uni.showToast({
            title: '请先登录',
            icon: 'none'
          })
          setTimeout(() => {
            uni.navigateTo({
              url: '/pages/login/login'
            })
          }, 1500)
        }
      } catch (error) {
        console.error('获取用户信息失败:', error)
        uni.showToast({
          title: '获取用户信息失败',
          icon: 'none'
        })
      }
    },
    
    async loadSubjects() {
      if (this.user_id==null) {
        console.warn('用户ID为空，无法加载历史对话')
        return
      }
      
      console.log('开始加载历史对话，用户ID:', this.user_id)
      this.loading = true
      try {
        const result = await getSubjects(this.user_id)
        console.log('获取历史对话结果:', result)
        if (result.success) {
          this.subjects = result.subjects || []
          console.log('加载的历史对话主题:', this.subjects)
        } else {
          console.error('加载历史对话失败:', result.message)
          uni.showToast({
            title: result.message || '加载失败',
            icon: 'none'
          })
        }
      } catch (error) {
        console.error('加载历史对话失败:', error)
        uni.showToast({
          title: '网络错误，请重试',
          icon: 'none'
        })
      } finally {
        this.loading = false
      }
    },
    
    async viewChatHistory(subject) {
      this.currentSubject = subject
      this.showChatDetail = true
      this.chatHistoryLoading = true
      
      try {
        const result = await getChatHistory(this.user_id, subject.subject_id)
        if (result.success) {
          this.chatHistory = result.chat_history || []
        } else {
          uni.showToast({
            title: result.message || '加载失败',
            icon: 'none'
          })
        }
      } catch (error) {
        console.error('加载对话历史失败:', error)
        uni.showToast({
          title: '网络错误，请重试',
          icon: 'none'
        })
      } finally {
        this.chatHistoryLoading = false
      }
    },
    
    closeChatDetail() {
      this.showChatDetail = false
      this.currentSubject = null
      this.chatHistory = []
    },
    
    goBack() {
      uni.navigateBack()
    },
    
    formatTime(timestamp) {
      if (!timestamp) return ''
      
      try {
        const date = new Date(timestamp)
        const now = new Date()
        const diff = now - date
        
        // 如果是今天
        if (date.toDateString() === now.toDateString()) {
          return date.toLocaleTimeString('zh-CN', { 
            hour: '2-digit', 
            minute: '2-digit' 
          })
        }
        
        // 如果是昨天
        const yesterday = new Date(now)
        yesterday.setDate(yesterday.getDate() - 1)
        if (date.toDateString() === yesterday.toDateString()) {
          return '昨天 ' + date.toLocaleTimeString('zh-CN', { 
            hour: '2-digit', 
            minute: '2-digit' 
          })
        }
        
        // 其他情况显示完整日期
        return date.toLocaleDateString('zh-CN') + ' ' + date.toLocaleTimeString('zh-CN', { 
          hour: '2-digit', 
          minute: '2-digit' 
        })
      } catch (error) {
        return timestamp
      }
    },
    
    continueChat(subject) {
      console.log('继续对话:', subject);
      // 存储当前对话到本地存储
      uni.setStorageSync('currentSubject',subject);
      uni.setStorageSync('continueChat', true);
      
      // 跳转到主页
      uni.redirectTo({
        url: '/pages/home/home'
      });
    },
    
    // 确认删除对话框
    confirmDelete(subject) {
      this.deleteSubject = subject;
      this.showDeleteConfirm = true;
    },
    
    // 取消删除
    cancelDelete() {
      this.showDeleteConfirm = false;
      this.deleteSubject = null;
    },
    
    // 执行删除
    async performDelete() {
      try {
        if (!this.deleteSubject) return;
        
        uni.showLoading({
          title: '删除中...',
          mask: true
        });
        
        // 调用删除API
        await deleteSubject(this.user_id, this.deleteSubject.subject_id);
        
        uni.hideLoading();
        
        // 从列表中移除已删除的主题
        this.subjects = this.subjects.filter(subject => 
          subject.subject_id !== this.deleteSubject.subject_id
        );
        
        // 关闭确认对话框
        this.showDeleteConfirm = false;
        this.deleteSubject = null;
        
        uni.showToast({
          title: '删除成功',
          icon: 'success',
          duration: 2000
        });
        
      } catch (error) {
        uni.hideLoading();
        console.error('删除历史对话失败:', error);
        
        uni.showToast({
          title: '删除失败，请重试',
          icon: 'none',
          duration: 2000
        });
      }
    },
  }
}
</script>

<style scoped>
.history-container {
  min-height: 100vh;
  background-color: #f5f5f5;
}

/* 导航栏样式 */
.nav-bar {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  padding: 20rpx 30rpx;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.nav-title {
  font-size: 36rpx;
  font-weight: bold;
}

.nav-actions {
  display: flex;
  align-items: center;
}

.back-btn {
  display: flex;
  align-items: center;
  padding: 10rpx 20rpx;
  background: rgba(255, 255, 255, 0.2);
  border-radius: 20rpx;
  font-size: 28rpx;
}

.back-icon {
  width: 36rpx;
  height: 36rpx;
  margin-right: 16rpx;
}

/* 历史列表样式 */
.history-list {
  height: calc(100vh - 120rpx);
  padding: 20rpx;
}

.history-item {
  background: white;
  border-radius: 16rpx;
  padding: 30rpx;
  margin-bottom: 20rpx;
  display: flex;
  justify-content: space-between;
  align-items: center;
  box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.1);
  transition: all 0.3s ease;
}

.history-item:active {
  background: #f8f9fa;
  transform: scale(0.98);
}

.subject-info {
  flex: 1;
}

.subject-name {
  display: block;
  font-size: 32rpx;
  font-weight: 500;
  color: #333;
  margin-bottom: 10rpx;
}

.subject-time {
  font-size: 24rpx;
  color: #999;
}

.action-buttons {
	display: flex;
	gap: 8px;
	align-items: center;
}

.continue-btn {
	background: #007AFF;
	color: white;
	padding: 8px 16px;
	border-radius: 16px;
	font-size: 12px;
	font-weight: 500;
}

.delete-btn {
	background: #FF3B30;
	color: white;
	padding: 8px 16px;
	border-radius: 16px;
	font-size: 12px;
	font-weight: 500;
}

/* 加载和空状态样式 */
.loading-container, .empty-container {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 200rpx;
}

.loading-text, .empty-text {
  font-size: 28rpx;
  color: #999;
}

/* 聊天详情弹窗样式 */
.chat-detail-modal {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 1000;
}

.modal-content {
  background: white;
  border-radius: 20rpx;
  width: 90vw;
  height: 80vh;
  overflow: hidden;
}

.modal-header {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  padding: 30rpx;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.modal-title {
  font-size: 32rpx;
  font-weight: bold;
}

.close-btn {
  font-size: 40rpx;
  width: 60rpx;
  height: 60rpx;
  display: flex;
  justify-content: center;
  align-items: center;
  border-radius: 50%;
  background: rgba(255, 255, 255, 0.2);
}

.chat-content {
  height: calc(80vh - 120rpx);
  padding: 20rpx;
}

.chat-message {
  margin-bottom: 30rpx;
}

.message-content {
  padding: 20rpx;
  border-radius: 16rpx;
  margin-bottom: 10rpx;
  max-width: 80%;
}

.user-content {
  background: #e3f2fd;
  margin-left: auto;
}

.ai-content {
  background: #f5f5f5;
  margin-right: auto;
}

.message-text {
  font-size: 28rpx;
  line-height: 1.5;
}

.message-time {
  font-size: 22rpx;
  color: #999;
  display: block;
  text-align: center;
}
.user-id {
  display: block;
  font-size: 22rpx;
  color: #666;
  margin-bottom: 8rpx;
  font-weight: bold;
}
.continue-chat-btn-container {
  display: flex;
  justify-content: center;
  margin: 40rpx 0;
}

.continue-chat-btn {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  border: none;
  border-radius: 50rpx;
  padding: 20rpx 60rpx;
  font-size: 28rpx;
  font-weight: bold;
  box-shadow: 0 4rpx 12rpx rgba(102, 126, 234, 0.3);
}

.continue-chat-btn:active {
	transform: scale(0.95);
}

/* 删除确认对话框样式 */
.delete-confirm-modal {
	position: fixed;
	top: 0;
	left: 0;
	right: 0;
	bottom: 0;
	background: rgba(0, 0, 0, 0.5);
	display: flex;
	justify-content: center;
	align-items: center;
	z-index: 1001;
}

.delete-confirm-modal .modal-content {
	background: white;
	border-radius: 20rpx;
	width: 80vw;
	max-width: 600rpx;
	padding: 0;
	overflow: hidden;
}

.delete-confirm-modal .modal-header {
	background: #FF3B30;
	color: white;
	padding: 30rpx;
	display: flex;
	justify-content: center;
	align-items: center;
}

.delete-confirm-modal .modal-body {
	padding: 40rpx 30rpx;
	text-align: center;
}

.confirm-text {
	font-size: 28rpx;
	color: #333;
	line-height: 1.5;
}

.delete-confirm-modal .modal-footer {
	display: flex;
	border-top: 1rpx solid #eee;
}

.cancel-btn, .confirm-delete-btn {
	flex: 1;
	text-align: center;
	padding: 30rpx 0;
	font-size: 28rpx;
	font-weight: 500;
}

.cancel-btn {
	color: #666;
	border-right: 1rpx solid #eee;
}

.confirm-delete-btn {
	color: #FF3B30;
	font-weight: bold;
}

.cancel-btn:active, .confirm-delete-btn:active {
	background: #f8f9fa;
}
</style>
